import torch

B, C = 4, 3
logits = torch.tensor([[2.0, 0.2, -0.3],
                       [-1.0, 1.5, 0.1],
                       [0.3, 0.1, 0.0],
                       [1.2, 0.5, -0.7]])  # (B, C)
target = torch.tensor([0, 1, 2, 0], dtype=torch.long)  # (B,)

# 1) log-softmax
log_probs = torch.log_softmax(logits, dim=1)  # (B, C)

# 2) 取每个样本正确类别的 log 概率
picked = log_probs[torch.arange(B), target]  # (B,)

# 3) 负对数并做平均（与 CrossEntropyLoss(reduction='mean') 等价）
loss_manual = -picked.mean()
print(loss_manual.item())
